// pages/lt/chat/chat.js
const app = getApp()
const util = require('../../../utils/util')
const db = wx.cloud.database()
const _ = db.command
var watcher
Page({

  /**
   * 页面的初始数据
   */
  data: {
    msg:'',
    exchange:'',
    name:'',
    messages:[
    ], //聊天记录
    head_img:'/images/logo.png',
    sex:0,
    tishi:''
  },

  // 改变当前消息
  current_msg(e){
    this.setData({
      msg:e.detail.value
    })
  },
  // 发送消息
  send(){
      let msgs = this.data.messages
      if(!(this.data.msg=='')){
      let msg = {status:'userr',message:this.data.msg,date:util.formatTime(new Date())}
      msgs.push(msg)
      this.setData({
        messages:msgs,
        msg:''
      })
      wx.setStorage({
        data: this.data.messages,
        key: this.data.exchange,
        complete:res=>{
          let msg2 = {status:'userl',message:msg.message,date:msg.date}
          db.collection('yw_exchange').where({openid2:app.globalData.userInfo._openid,openid:this.data.exchange}).update({
            data:{
              msg: _.push(msg2)
            }
          })
        }
      })
    }
      
  },
  // 获取聊天记录
  getMessages(){
    db.collection('yw_exchange').where({openid:app.globalData.userInfo._openid,openid2:this.data.exchange}).get().then(res=>{
        if(!(res.data[0].msg.length==0)){
          let msgs = this.data.messages
          msgs = msgs.concat(res.data[0].msg)
          this.setData({
            messages:msgs
          })
          wx.setStorage({
            data: this.data.messages,
            key: this.data.exchange,
            complete:()=>{
              db.collection('yw_exchange').where({openid:app.globalData.userInfo._openid,openid2:this.data.exchange}).update({
                data:{
                  msg:[]
                }
              }).then(res=>{
                console.log('莫名其妙')
              })
            }
          })
    }
    })
  },
  // 保存信息
  save(){
    // let exchange['id']
    // wx.setStorage({
    //   data: '',
    //   key: 'Messages',
    // })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      exchange:options.userId,
      name:options.name,
      sex:options.sex,
      tishi:options.tishi
    })
    wx.getStorage({
      key: options.userId,
      success:res=>{
          this.setData({
            messages:res.data
          })
      },
      fail:err=>{
        console.log(err)
      },
      complete:()=>{
        this.getMessages();
      }
    })
      // wx.getStorage({
      //   key: 'Messages',
      //   success:res=>{
      //     console.log(res)
      //   },
      //   fail:err=>{
      //     console.log(err)
      //   }
      // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    watcher = db.collection('yw_exchange').where({openid:app.globalData.userInfo._openid,openid2:this.data.exchange}).watch({
      onChange:res=>{
        res.type=='init'?'':this.getMessages()
      },
      onError:err=>{
        console.log(err)
      }
    })
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

// 取消监听
  bug(){
    watcher.close()
    wx.navigateBack({
      delta: 2,
    })
  }
})